package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.OcrUtil;
import com.heima.utils.ProtostuffUtil;
import com.heima.utils.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.AutoScanService;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmUserService;
import com.hema.feign.apis.Article.IArticleClient;
import com.hema.feign.apis.Schedule.IScheduleClient;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AutoScanServiceImpl implements AutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmChannelService wmChannelService;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private IScheduleClient scheduleClient;



    @Override
    public void antoScanWmNews(Long newsId) throws Exception {
        //判空
        if (newsId==null){
            return;
        }
        //根据newsId查询WmNews信息
        WmNews wmNews = wmNewsMapper.selectById(newsId);

        //提取新闻文字
        String title = wmNews.getTitle();
        String content = wmNews.getContent();
        String text = getText(title, content);

        //提取新闻图片
        String images = wmNews.getImages();
        List<byte[]> imagelist = getImage(images, content);
        //图片扫描敏感词检测
        String check = ocrCheck(imagelist);
        text=text+check;
        //自建敏感词检测
        boolean sensitive = sensitive(text);
        if (!sensitive){
            updateWmNews(2,"自检审核没通过",null,newsId.intValue());
            return;
        }
        //调用阿里云文字审核
        Map textScan = greenTextScan.greeTextScan(text);
        Boolean aboolean = suggestionis(textScan, newsId.intValue());
        if (!aboolean){
            log.warn("文字审核失败");
            return;
        }

        //调用阿里云图片审核
        Map imageScan = greenImageScan.imageScan(imagelist);
        Boolean bboolean = suggestionis(imageScan,newsId.intValue());
        if (!bboolean){
            log.warn("图片审核失败");
            return;
        }
        //ArtileClient远程调用
        ArticleDto dto=wmNews2ArticleDto(wmNews);
        ResponseResult responseResult = iArticleClient.saveArticle(dto);
        if (responseResult==null||responseResult.getCode()!=200){
            log.warn("文章保存失败");

            return;
        }
        Long articleId = (Long) responseResult.getData();
        //更新WmNews
        updateWmNews(9,"审核通过",articleId,newsId.intValue());

    }
    //消费任务
    @Scheduled(fixedRate = 1000)
    public void scanNewsByTask (){
        System.out.println("获取任务执行中----------");
        ResponseResult responseResult = scheduleClient.poll();
        if (responseResult==null || responseResult.getCode()!=200){
            return;
        }
        Object data = responseResult.getData();
        String s = JSON.toJSONString(data);
        Task task = JSON.parseObject(s, Task.class);
        byte[] parameters = task.getParameters();
        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
        Integer id = wmNews.getId();
        try {
            antoScanWmNews(id.longValue());
            System.out.println("开始审核保存文章了");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    //图片扫描敏感词检测
    private String ocrCheck(List<byte[]> images) throws IOException, TesseractException {
        //判空
        if (CollectionUtils.isEmpty(images)){
            return "";
        }
        //遍历集合
        StringBuilder builder = new StringBuilder();
        for (byte[] image : images) {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(image);
            //调用工具类
            BufferedImage read = ImageIO.read(byteArrayInputStream);
            String text = OcrUtil.doOcr(read);
            //拼接字符串
            builder.append("_").append(text);
        }
        //返回结果
        return builder.toString();
    }
    //自检敏感词检测
    private boolean sensitive(String text){
        //判空
        if (StringUtils.isBlank(text)){
            return true;
        }
        //到mysql中查询所以敏感词
        LambdaQueryWrapper<WmSensitive> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(WmSensitive::getSensitives);
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(wmSensitives)) {
            return  true;
        }
        List<String> collect = wmSensitives.stream().filter(Objects::nonNull).map(WmSensitive::getSensitives).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)){
            return true;
        }
        //进行初始化
        SensitiveWordUtil.initMap(collect);
        //进行敏感词匹配
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);

        //返回结果
        return CollectionUtils.isEmpty(map);

    }

    //声明入参
    public ArticleDto wmNews2ArticleDto (WmNews wmNews){
        if (wmNews == null ){
            return null;
        }
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,dto);
        dto.setLayout(wmNews.getType());
        Integer channelId = wmNews.getChannelId();
        if (channelId != null){
            WmChannel channel = wmChannelService.getById(channelId);
            if (channel != null){
                dto.setChannelName(channel.getName());
            }

        }
        //获取作者名，作者ID
        Integer userId = wmNews.getUserId();
        if (userId != null){
            dto.setAuthorId(userId.longValue());
            WmUser wmUser = wmUserService.getById(userId);
            if (wmUser!=null){
                dto.setAuthorName(wmUser.getName());
            }
        }
        return dto;

    }
    //更新WmNews
    private Boolean updateWmNews(Integer status,String reason,Long articleId,Integer newsId){
        //创建一个Wmnews对象并赋值
        WmNews wmNews = new WmNews();
        wmNews.setStatus(status.shortValue());
        wmNews.setReason(reason);
        wmNews.setId(newsId);
        //如果acticleId==null就不设置acticleId的值
        if (articleId!=null){
            wmNews.setArticleId(articleId);
        }
       return wmNewsMapper.updateById(wmNews) > 0;
    }
    //图片和文字审核
    private boolean suggestionis(Map result,Integer newsId){
        //判空
        if (result==null){
            log.warn("结果为空");
            return true;
        }
        String suggestion = (String) result.get("suggestion");
        //如果等于pass直接返回true
        if ("pass".equals(suggestion)){
            return true;
        }
        //等于block调用更新Wmnews方法
        if ("block".equals(suggestion)){
             updateWmNews(2,"不通过",null,newsId);
        }//等于review调用更新Wmnews方法
        if ("review".equals(suggestion)){
            updateWmNews(3,"转人工审核",null,newsId);
        }
        return true;
    }
    //提取新闻文字
    private String getText(String title,String content){
        //判空
        if (StringUtils.isEmpty(content)){
            return title;
        }
        StringBuilder stringBuilder=new StringBuilder();
        List<Map> maps = JSON.parseArray(content, Map.class);
        //如果不为空
        if (!CollectionUtils.isEmpty(maps)) {
            //遍历集合如果type等于text就获取他的value值
            for (Map item : maps) {
                if (CollectionUtils.isEmpty(item)) {
                    continue;
                }
                Object type = item.get("type");
                if ("text".equals(type)){
                    String value = (String) item.get("value");
                    stringBuilder.append(value);
                }
            }
        }
        //将title和content结果组合在一起
        StringBuilder append = stringBuilder.append("_").append(title);
        String Text = append.toString();
        //返回
        return Text;
    }
    //提取新闻图片
    private List<byte[]> getImage(String images,String content){
        List<String> list = new ArrayList<>();
        //如果images不等于空
        if (StringUtils.isNotEmpty(images)){
            //用","分割成数组，然后将数组转换为list集合
            String[] split = images.split(",");
            List<String> asList = Arrays.asList(split);
            //将转换好的list集合添加到提前定义好的大的list数组
            list.addAll(asList);

        }
        //如果content不等于空就转换成集合
        if (StringUtils.isNotEmpty(content)){
            List<Map> maps = JSON.parseArray(content, Map.class);
            //如果maps不等于空，遍历maps
            if (!CollectionUtils.isEmpty(maps)) {
                for (Map item : maps) {
                    if (CollectionUtils.isEmpty(item)){
                        continue;
                    }
                    Object type = item.get("type");
                    //如果type等于image就过去他的valye值
                    if ("image".equals(type)){
                        String value = (String) item.get("value");
                        //将获取好的valye值添加到准备好的list集合里
                        list.add(value);
                    }
                }
            }
        }
        List<byte[]> byteslist = new ArrayList<>();
        //遍历提取准备好的list集合
        for (String s : list) {
            //利用minio的方法将他们转换为byte数组
            byte[] bytes = minIoTemplate.downLoadFile(s);
            //将bytes数组添加到定义好的byte集合
            byteslist.add(bytes);
        }
        //返回byte集合
        return byteslist;
    }
}
